package com.xxx.dorm.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {


    /**
     * 将用户名和密码，存入cookie中
     * @param cookieName
     * @param time
     * @param username
     * @param password
     * @param request
     * @param response
     */
    public static void addCookie(String cookieName, int time,String username,String password,
                        HttpServletRequest request, HttpServletResponse response){

        Cookie cookie = getCookieByName(cookieName,request);
        if(cookie == null){
            cookie = new Cookie(cookieName,username+"_"+password);
        }else{
            cookie.setValue(username+"_"+password);
        }
        cookie.setMaxAge(time);//设置cookie有效时间
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

    }

    /**
     * 查看是否存在key为cookieName的cookie
     * @param cookieName
     * @param request
     * @return
     */
    public static Cookie getCookieByName(String cookieName,HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(cookieName)){
                    return cookie;
                }
            }
        }
        return null;
    }
}
